package com.xie.smfs.entity;

import com.xie.smfs.item.RedGhostCandleItem;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.damage.DamageTypes;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;
import java.util.Random;

public class LostGhostEntity extends GhostEntity {
    private final Random random = new Random();
    private int attackCooldown = 0;


    public LostGhostEntity(EntityType<? extends GhostEntity> entityType, World world) {
        super(entityType, world, true, 0, 32.0); // 启用鬼域，等级0，半径32
        this.ghostLevel = 1; // 设置危险等级A
        this.setKillingRulesEnabled(true); // 启用杀人规则以允许executeAttack触发
    }

    @Override
    public void tick() {
        super.tick();

        // 处理攻击冷却
        if (attackCooldown > 0) {
            attackCooldown--;
        }
    }

    @Override
    protected boolean shouldAttackPlayer(PlayerEntity player) {
        // 总是可以攻击玩家，但实际效果由executeAttack控制
        return !isSuppressed() && !isDeadlocked() && !RedGhostCandleItem.isHoldingCandle(player);
    }

    @Override
    protected void executeAttack(PlayerEntity player) {
        if (attackCooldown > 0) return; 

        int effect = random.nextInt(4) + 1;
        Text message = Text.empty();

        switch (effect) {
            case 1 -> {
                message = Text.literal("你忘记了走路...");
                player.addStatusEffect(new StatusEffectInstance(StatusEffects.SLOWNESS, Integer.MAX_VALUE, 255, false, false));
            }
            case 2 -> {
                message = Text.literal("你忘记了你的眼睛...");
                player.addStatusEffect(new StatusEffectInstance(StatusEffects.BLINDNESS, Integer.MAX_VALUE, 255, false, false));
            }
            case 3 -> {
                message = Text.literal("你忘记了自己...");
                player.kill();
            }
            case 4 -> {
                message = Text.literal("你忘记了呼吸...");
                RegistryEntry<DamageType> drownDamageType = getWorld().getRegistryManager()
                        .get(RegistryKeys.DAMAGE_TYPE)
                        .getEntry(DamageTypes.DROWN).orElse(null);
                if (drownDamageType != null) {
                    player.damage(new DamageSource(drownDamageType), Float.MAX_VALUE);
                } else {
                    player.damage(player.getDamageSources().drown(), Float.MAX_VALUE);
                }
            }
        }
        player.sendMessage(message, true);
        attackCooldown = 600;
    }
}